package com.drinks.yiniang.ui.activity.user.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.wallet.RechargePackageAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.common.help.PayManager;
import com.drinks.yiniang.entity.event.PayWXEventBus;
import com.drinks.yiniang.entity.pay.AliPayJson;
import com.drinks.yiniang.entity.pay.WeiXinPayJson;
import com.drinks.yiniang.entity.user.wallet.RechargePackageJson;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.common.WebActivity;
import com.drinks.yiniang.ui.widget.dialog.ContactServiceDialog;
import com.drinks.yiniang.ui.widget.dialog.PayDialog;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


/**
 * 充值页面
 *
 * @author han
 * @date 2019/09/06
 */
public class RechargeActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, PayDialog.OnPayListener, PayManager.PayResultListener {

    //nav bar
    private NavigationBarLayout nav_bar_recharge;
    //套餐列表
    private BaseRecyclerView rcv_recharge_package;
    //footer view
    //充值套餐说明
    private TextView tv_recharge_pkg_explain;

    private RechargePackageAdapter mPackageAdapter;

    private PayManager mPayManager;

    //套餐id
    private String mPackageId;

    @Override
    protected void initView() {
        nav_bar_recharge = findViewById(R.id.nav_bar_recharge);

        rcv_recharge_package = findViewById(R.id.rcv_recharge_package);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mPayManager = new PayManager(this);
        initAdapter();
        getPackageList();
    }

    private void initAdapter() {
        rcv_recharge_package.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_recharge_package.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mPackageAdapter = new RechargePackageAdapter(mContext, new ArrayList<RechargePackageJson.RechargePackageData>());
        mPackageAdapter.addFooterView(getFooterView());
        mPackageAdapter.setHeaderFooterEmpty(false, true);
        mPackageAdapter.setCommonEmpty(getLayoutInflater(), rcv_recharge_package);
        mPackageAdapter.bindToRecyclerView(rcv_recharge_package);
    }

    //获取header
    private View getFooterView() {
        View mFooterView = getLayoutInflater().inflate(R.layout.footer_recharge_package_explain, (ViewGroup) rcv_recharge_package.getParent(), false);

        tv_recharge_pkg_explain = mFooterView.findViewById(R.id.tv_recharge_pkg_explain);

        tv_recharge_pkg_explain.setOnClickListener(this);

        return mFooterView;
    }

    @Override
    protected void initListener() {
        nav_bar_recharge.setOnNavgationBarClickListener(this);

        mPackageAdapter.setOnItemClickListener(this);
        mPayManager.setPayResultListener(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void widgetClick(View v) {
        if (v.getId() == R.id.tv_recharge_pkg_explain) {//充值套餐说明
            Intent intent = new Intent(mContext, WebActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_recharge;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        ContactServiceDialog dialog = ContactServiceDialog.newInstance();

        dialog.show(getSupportFragmentManager(), Constants.TAG_CONTACT_SERVICE_DIALOG);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        RechargePackageJson.RechargePackageData data = mPackageAdapter.getItem(position);

        if (data == null) {
            return;
        }

        mPackageId = data.getId();

        PayDialog dialog = PayDialog.newInstance(false);
        dialog.show(getSupportFragmentManager(), Constants.TAG_PAY_DIALOG);
    }

    @Override
    public void onPaySuccess(String msg) {
        setPayResult();
    }

    @Override
    public void onPayFail(String errCode, String errMsg) {

    }

    @Override
    public void onPayClick(int payType) {
        if (StringUtils.isEmpty(mPackageId)) {
            ToastUtils.showShort(getString(R.string.text_select_recharge_package));
            return;
        }

        switch (payType) {
            case PayManager.PAY_CHANNEL_ALIPAY://支付宝支付
                doPayByAliPay();
                break;
            case PayManager.PAY_CHANNEL_WX://微信支付
                doPayByWeiXinPay();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPayDismiss() {

    }

    @Override
    public void onPayClose() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PayWXEventBus event) {
        if (PayWXEventBus.PAY_STATUS_SUCCESS == event.getPayStatus()) {//支付成功
            //发送刷新信息event
            if (PayManager.PAY_TYPE_RECHARGE_PAY.equals(event.getPayPage())) {
                setPayResult();
            }
        }
    }

    private void setPayResult() {
        setResult(Constants.RESULT_CODE_NORMAL);
        finish();
    }

    //支付宝充值
    private void doPayByAliPay() {
        showLoadingDialog();

        UserApiIO.getInstance().doRechargeByAlipay(mPackageId, new APIRequestCallback<AliPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AliPayJson res) {
                mPayManager.slingAiPay(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //微信支付
    private void doPayByWeiXinPay() {
        showLoadingDialog();

        UserApiIO.getInstance().doRechargeByWeiXinPay(mPackageId, new APIRequestCallback<WeiXinPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(WeiXinPayJson res) {
                mPayManager.slingWXPay(res.getData(), PayManager.PAY_TYPE_RECHARGE_PAY);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取套餐列表
    private void getPackageList() {
        showLoadingDialog();

        UserApiIO.getInstance().getRechargePackageList(new APIRequestCallback<RechargePackageJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RechargePackageJson res) {
                mPackageAdapter.setNewData(res.getData());
                mPackageAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mPackageAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
